package com.wanqing.controller.admin;

import com.wanqing.dto.VoucherDTO;
import com.wanqing.dto.VoucherPageQueryDTO;
import com.wanqing.result.PageResult;
import com.wanqing.result.Result;
import com.wanqing.service.VoucherService;
import com.wanqing.vo.VoucherVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 书店优惠券管理
 */
@RestController
@RequestMapping("/admin/voucher")
@Tag(name = "优惠券管理接口")
@Slf4j
public class VoucherController {
    @Autowired
    private VoucherService voucherService;

    /**
     * 创建新优惠券（包含规则）
     *
     * @param voucherDTO 优惠券信息DTO
     * @return 创建结果
     */
    @PostMapping
    @Operation(summary = "创建优惠券")
    public Result<String> createVoucher(@RequestBody @Validated VoucherDTO voucherDTO) {
        voucherService.createVoucher(voucherDTO);
        return Result.success();
    }

    /**
     * 根据ID查询优惠券详情
     *
     * @param id 优惠券ID
     * @return 优惠券详情VO
     */
    @GetMapping("/{id}")
    @Operation(summary = "查询优惠券详情")
    public Result<VoucherVO> getVoucherById(@PathVariable Long id) {
        VoucherVO voucherVO = voucherService.getVoucherDetail(id);
        return Result.success(voucherVO);
    }

    /**
     * 分页查询优惠券列表
     *
     * @param voucherPageQueryDTO
     * @return
     */
    @GetMapping
    @Operation(summary = "分页查询优惠券列表")
    public Result<PageResult> getVoucherList(VoucherPageQueryDTO voucherPageQueryDTO) {
        PageResult pageResult = voucherService.getVoucherList(voucherPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 更新优惠券信息
     *
     * @param voucherDTO 优惠券更新信息
     * @return 更新结果
     */
    @PutMapping
    @Operation(summary = "更新优惠券")
    public Result updateVoucher(@RequestBody @Valid VoucherDTO voucherDTO) {
        voucherService.updateVoucher(voucherDTO);
        return Result.success();
    }

    /**
     * 上下架优惠券
     *
     * @param id     优惠券ID
     * @param status 状态：1-上架；2-下架
     * @return 操作结果
     */
    @PatchMapping("/{id}/{status}")
    @Operation(summary = "更新优惠券状态（上下架）")
    public Result<Boolean> updateVoucherStatus(
            @PathVariable Long id,
            @PathVariable Byte status) {
        voucherService.updateVoucherStatus(id, status);
        return Result.success();
    }

    @DeleteMapping
    @Operation(summary = "批量删除优惠券")
    public Result<String> deleteVoucher(@RequestBody List<Long> ids) {
        log.info("批量删除优惠券：{}", ids);
        if (ids == null || ids.isEmpty()) {
            return Result.error("优惠券删除失败");
        }
        voucherService.deleteBatch(ids);
        return Result.success();
    }
}
